//
//  CallViewController.m
//  NetPhone
//
//  Created by intel intel on 12-4-26.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CallViewController.h"
#import "ViewController.h"
#import "GlobalVar.h"
#import "MBProgressHUD.h"
#import "Infro.h"
//#import "CREngine.h"
#import "iToast.h"
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>
//#import "ipjsua_app_callback.h"
#import "XMLReader.h"
#import "GDataXMLNode.h"
#import "EGOImageView.h"
#import "BannerView.h"
//
@implementation CallViewController
@synthesize number;
@synthesize name;
@synthesize callNum;
static CallViewController *shareCallViewControllerInstance = nil;

+(CallViewController *) sharedInstance
{
    return shareCallViewControllerInstance;
}

+(void)callWithNumber:(NSString *)_number name:(NSString *)_name
{
    CallViewController *call = [[[CallViewController alloc]init]autorelease];
    call.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    NSString* showNumCode=[[NSUserDefaults standardUserDefaults] objectForKey:@"showNum"];
    NSString* quhao=[[NSUserDefaults standardUserDefaults] objectForKey:@"bendiquhao"];
    if ([showNumCode isEqualToString:@"NO"])
    {
        if ([_number length]>3&&[_number length]<=8)
        {
            call.callNum=[NSString stringWithFormat:@"%@%@",quhao,_number];
        }else if (([_number length]>8&&[_number length]<=30)||[_number length]==3){
            call.callNum=[NSString stringWithFormat:@"%@",_number];
        }
        //9表示不显示号
        call.number=[NSString stringWithFormat:@"%d%@",9,call.callNum];
        //NSLog(@"不显示了");
    }else
    {
        //NSLog(@"显示了");
        if ([_number length]>3&&[_number length]<=8) {
            if (quhao)
            {
                call.callNum=[NSString stringWithFormat:@"%@%@",quhao,_number];
            }else
            {
                call.callNum=[NSString stringWithFormat:@"%@",_number];
            }
        }else if (([_number length]>8&&[_number length]<=30)||[_number length]==3){
            call.callNum=[NSString stringWithFormat:@"%@",_number];
        }
        call.number=call.callNum;
        NSLog(@"你拨打的号码是:%@",call.number);
    }
    call.name = _name;
    [[ViewController sharedInstance]presentModalViewController:call animated:YES];
}

+(void)callWithNumber:(NSString *)_number name:(NSString *)_name AndDialType:(int)dialType
{
    CallViewController *call = [[[CallViewController alloc]init]autorelease];
    call.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    NSString* showNumCode=[[NSUserDefaults standardUserDefaults] objectForKey:@"showNum"];
    NSString* quhao=[[NSUserDefaults standardUserDefaults] objectForKey:@"bendiquhao"];
    if ([showNumCode isEqualToString:@"NO"])
    {
        if ([_number length]>3&&[_number length]<=8)
        {
            if (quhao)
            {
                call.callNum=[NSString stringWithFormat:@"%@%@",quhao,_number];
            }else
            {
                call.callNum=[NSString stringWithFormat:@"%@",_number];
            }
        }else if (([_number length]>8&&[_number length]<=30)||[_number length]==3)
        {
            call.callNum=[NSString stringWithFormat:@"%@",_number];
        }
        call.number=[NSString stringWithFormat:@"%d%@",9,call.callNum];
        //NSLog(@"不显示了");
    }else
    {
        //NSLog(@"显示了");
        if ([_number length]>3&&[_number length]<=8) {
            if (quhao)
            {
                call.callNum=[NSString stringWithFormat:@"%@%@",quhao,_number];
            }else
            {
                call.callNum=[NSString stringWithFormat:@"%@",_number];
            }
        }else if (([_number length]>8&&[_number length]<=30)||[_number length]==3){
            call.callNum=[NSString stringWithFormat:@"%@",_number];
        }
        call.number=call.callNum;
        NSLog(@"AndDialType＝＝你拨打的号码是:%@",call.number);
    }
    call.name = _name;
    call.dialType=dialType;
    //放入ViewController显示容器
    [[ViewController sharedInstance]presentModalViewController:call animated:YES];
}
-(void)viewDidDisappear:(BOOL)animated
{
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:nil forKey:@"QBKey"];
    [defaults synchronize];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(feedBackCallState:) name:@"CALLSTATENOTIFICATION" object:nil];
    bg = [[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"callbg"]]autorelease];
    bg.userInteractionEnabled=YES;
    bg.frame = CGRectMake(0, 0, IPHONE_W, IPHONE_H);
    [self.view addSubview:bg];
    self.labStatus = [[[UILabel alloc]initWithFrame:CGRectMake(0, 20, 320, 40)]autorelease];
    self.labStatus.font = [UIFont boldSystemFontOfSize:12];
    self.labStatus.textColor = [UIColor whiteColor];
    self.labStatus.shadowColor = [UIColor whiteColor];
    self.labStatus.backgroundColor = [UIColor clearColor];
    self.labStatus.textAlignment = NSTextAlignmentCenter;
    self.labStatus.text = @"正在拨号，请稍候...";
    [self.view addSubview:self.labStatus];
    UILabel* phoneNameLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, IPHONE_H-120, 320, 30)];
    phoneNameLabel.font=[UIFont boldSystemFontOfSize:16];
    phoneNameLabel.textColor=[UIColor darkGrayColor];
    phoneNameLabel.backgroundColor=[UIColor clearColor];
    phoneNameLabel.textAlignment=NSTextAlignmentCenter;
    phoneNameLabel.text=self.name;
    [self.view addSubview:phoneNameLabel];
    [phoneNameLabel release];
    
    UILabel* phoneNumLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, IPHONE_H-100, 320, 30)];
    phoneNumLabel.font=[UIFont boldSystemFontOfSize:14];
    phoneNumLabel.textColor=[UIColor darkGrayColor];
    phoneNumLabel.backgroundColor=[UIColor clearColor];
    phoneNumLabel.textAlignment=NSTextAlignmentCenter;
    NSString *nsStrNum=self.number;
    NSString* showNumCode=[[NSUserDefaults standardUserDefaults] objectForKey:@"showNum"];
    if ([showNumCode isEqualToString:@"NO"])
    {
        nsStrNum = [nsStrNum substringWithRange:NSMakeRange(1, nsStrNum.length-1)];
    }else{
        phoneNumLabel.text= nsStrNum;
    }
    phoneNumLabel.text=nsStrNum;
    [self.view addSubview:phoneNumLabel];
    [phoneNumLabel release];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, self.view.frame.size.height - 92 + (92-53) /2, 280, 53);
    button.titleLabel.font = [UIFont boldSystemFontOfSize:22];
    [button addTarget:self action:@selector(callBack:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    //[self performSelector:@selector(call:) withObject:[GlobalVar getTheBestUrl] afterDelay:2];
    [self call:[GlobalVar getTheBestUrl]];
    
}

#pragma 接听界面广告
-(void)showAdv
{
    
    
   
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    pageNum=[defaults integerForKey:@"jietingImagecount"];
    if (pageNum>0)
    {
        CGRect frame=CGRectMake(0, 50, IPHONE_W, IPHONE_H-200);
        barnnerView=[[BannerView alloc]initWithFrame:frame];
        [bg addSubview:barnnerView];
        NSMutableArray *nsMuArrImg =[[NSMutableArray alloc]initWithCapacity:5];
        for (int i=0; i<pageNum; i++)
        {
            NSString* totalAdStr= [defaults objectForKey:[NSString stringWithFormat:@"callStr%d",i]];
            [nsMuArrImg addObject:totalAdStr];
        }
        [barnnerView initData:nsMuArrImg imgBounds:CGRectMake(0, 0, IPHONE_W, IPHONE_H-200)];
        [barnnerView start];
    }
    NSLog(@"====接听界面广告====");
}

-(void)callPlayerStartToPlay
{
    NSString* soundPath=[[NSBundle mainBundle]pathForResource:@"ring" ofType:@"mp3"];
    NSURL* soundUrl=[NSURL fileURLWithPath:soundPath];
    callPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:soundUrl error:nil];
    callPlayer.numberOfLoops=-1;
    callPlayer.volume=0.3;
    [callPlayer prepareToPlay];
    if ([callPlayer isPlaying])
    {
        [callPlayer stop];
    }else
    {
        [callPlayer play];
    }
}

-(void)call:(NSString*)theBestUrl
{
    if (_dialType==0)
    {
        //NSLog(@"直拨");
        //pjsuaMakeCall([number UTF8String]);
    }else if (_dialType==1)
    {
        NSString *UserName = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"LOGIN_USER_KEY"]];
        NSString* clientNum=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"LOGIN_USER_NUMBER"]];
        NSString* _prMD5=[NSString stringWithFormat:@"%@%@%@%@",UserName,SOFT_ID,number,@"ysw"];
        NSString* MD5Str=[GlobalVar md5Str:_prMD5];
        startTime=[GlobalVar getTimeChuo];
        
        if ([GlobalVar sharedInstance].blnUseProxy==YES)
        {
            self.requestCallingData=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",origin_url_prefix,@"call.php"]]];
            [self.requestCallingData setProxyPort:ProxyPort];
            [self.requestCallingData setProxyHost:[GlobalVar getTheBestIp]];//
        }else
        {
            self.requestCallingData=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",theBestUrl,@"proxy.php"]]];
            [self.requestCallingData setPostValue:origin_url_prefix forKey:@"apiurl"];
            [self.requestCallingData setPostValue:@"call" forKey:@"act"];
        }
        [self.requestCallingData setDelegate:self];
        [self.requestCallingData setTimeOutSeconds:TIME_OUT_SECONDS];
        [self.requestCallingData setPostValue:UserName forKey:@"mobile"];
        [self.requestCallingData setPostValue:SOFT_ID forKey:@"softid"];
        [self.requestCallingData setPostValue:number forKey:@"called"];
        [self.requestCallingData setPostValue:clientNum forKey:@"account"];
        [self.requestCallingData setPostValue:MD5Str forKey:@"md5"];
        [self.requestCallingData setPostValue:MULTIAGENTSWITCH forKey:@"multiAgent"];
        [self.requestCallingData setPostValue:NETWORKSTATE forKey:@"apn"];
        [self.requestCallingData setPostValue:SOFT_VER forKey:@"version"];
        [self.requestCallingData setPostValue:@"1" forKey:@"call2"];
        [self.requestCallingData setDidFinishSelector:@selector(oncallSuccess:)];
        [self.requestCallingData setDidFailSelector:@selector(oncallFail:)];
        [self.requestCallingData setShouldAttemptPersistentConnection:NO];
        [self.requestCallingData startAsynchronous];
        
    }
}
-(void)testBaidu
{
    ASIHTTPRequest* request=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(testBaiduSuccess:)];
    [request setDidFailSelector:@selector(testBaiduFail:)];
    [request setShouldAttemptPersistentConnection:NO];
    [request startAsynchronous];
}

-(void)testBaiduSuccess:(ASIHTTPRequest*)request
{
    NSString* result=[request responseString];
    //NSLog(@"Baidu结果:%@",result);
    endTime=[GlobalVar getTimeChuo];
    UInt64 time_cha=[GlobalVar preRequestTime:startTime AndAfterRequestTime:endTime];
    NSString* recod=[NSString stringWithFormat:@"Baidu|%llu \n",time_cha];
    NSLog(@"Baidu写入记录:%@",recod);
    [GlobalVar writeTheInfoToTheLocal:recod];
    
}

-(void)testBaiduFail:(ASIHTTPRequest*)request
{
    NSString* time_out_info=[NSString stringWithFormat:@"%@测试Baidu超时 %@",[[[[[[request url] absoluteString] componentsSeparatedByString:@"/"] objectAtIndex:2] componentsSeparatedByString:@":"] objectAtIndex:0],[GlobalVar getBundleIdentifierAndCurrentDate]];
    [GlobalVar writeTheInfoToTheLocal:time_out_info];
}

-(void)oncallSuccess:(ASIHTTPRequest*)request
{
    NSLog(@"===requestCallingData===111===");
    [self testBaidu];
    if (_dialType==1)
    {
        [self callPlayerStartToPlay];
    }
    NSString* result=[request responseString];
    endTime=[GlobalVar getTimeChuo];
    UInt64 time_cha=[GlobalVar preRequestTime:startTime AndAfterRequestTime:endTime];
    NSString* recod=[NSString stringWithFormat:@"\n%@|%d|%@|call|%@|%@|%@|%llu \n",[GlobalVar getBundleIdentifierAndCurrentDate],[GlobalVar getCarrierNetWorkSignal],[[[[[[request url] absoluteString] componentsSeparatedByString:@"/"] objectAtIndex:2] componentsSeparatedByString:@":"] objectAtIndex:0],SOFT_ID,[GlobalVar getNetWorkStates],[GlobalVar loginUserKey],time_cha];
    //NSLog(@"打电话写入记录:%@",recod);
    [GlobalVar writeTheInfoToTheLocal:recod];
    if ([result length]>0 && [result rangeOfString:@"|"].location!=NSNotFound)
    {
        NSArray* callArr=[result componentsSeparatedByString:@"|"];
        if (callArr.count==2 && [callArr[0] isEqualToString:@"1"])
        {
            NSString *msg = (NSString *)callArr[1];
           // NSLog(@"===打电话返回=msg===%@",msg);
            if ([msg rangeOfString:@"QB"].location!=NSNotFound)
            {
                NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
                [defaults setObject:msg forKey:@"QBKey"];
                [defaults synchronize];
            }else
            {
                NSString* msg=callArr[1];
                NSString* value=msg;
                self.labStatus.text=value;
            }
        }
    }else
    {
        [GlobalVar writeTheInfoToTheLocal:@"收到数据包为空，重新选线路"];
        [GlobalVar alert:ERRORCODE];
        [[SocketDispatch sharedInstance] socketCheck];
    }

   
}

-(void)oncallFail:(ASIHTTPRequest*)request
{
    //NSLog(@"===requestCallingData===222===");
    [GlobalVar alert:ERRORCODE];
    [[SocketDispatch sharedInstance] socketCheck];
    NSString* time_out_info=[NSString stringWithFormat:@"%@超时  %@",[[[[[[request url] absoluteString] componentsSeparatedByString:@"/"] objectAtIndex:2] componentsSeparatedByString:@":"] objectAtIndex:0],[GlobalVar getBundleIdentifierAndCurrentDate]];
    [GlobalVar writeTheInfoToTheLocal:time_out_info];
}
-(void)alert:(NSString *)msg
{
    MBProgressHUD *HUD = [[[MBProgressHUD alloc] initWithView:self.view]autorelease];
    HUD.removeFromSuperViewOnHide = YES;
	[self.view addSubview:HUD];
	[HUD setLabelFont:[UIFont systemFontOfSize:12]];
    HUD.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-warning.png"]] autorelease];
    HUD.mode = MBProgressHUDModeCustomView;
    HUD.labelText = msg;
	[HUD show:YES];
    [HUD hide:YES afterDelay:3];
}
#pragma mark呼叫状态
-(void)feedBackCallState:(NSNotification*)notify
{
   
    NSString* state=[notify object];
    int state_intVal=[state intValue];
    switch (state_intVal)
    {
        case 1:
           
            [NSThread detachNewThreadSelector:@selector(changeText:) toTarget:self withObject:@"开始呼叫对方，请稍后..."];
            break;
        case 3:
         
            [NSThread detachNewThreadSelector:@selector(changeText:) toTarget:self withObject:@"正在等待对方接听，请稍后..."];
            break;
        case 5:
            
            [NSThread detachNewThreadSelector:@selector(changeText:) toTarget:self withObject:@"00:00"];
            break;
        case 6:
            
            [NSThread detachNewThreadSelector:@selector(changeText:) toTarget:self withObject:@"正在挂断"];
            break;
        default:
            break;
    }
}

-(void)changeText:(NSString*)theString
{
    NSLog(@"====changeText===%@",theString);
    self.labStatus.text=theString;
    if ([theString isEqualToString:@"00:00"])
    {
        [self performSelectorOnMainThread:@selector(createTimer) withObject:nil waitUntilDone:YES];
        
    }else if ([theString isEqualToString:@"正在挂断"])
    {
        [self clearnTimer];
        [self dismissModalViewControllerAnimated:YES];
        iToast *toast=[iToast makeText:@"通话已断开"];
        [toast show];
        //[self performSelector:@selector(returnBackView) withObject:nil afterDelay:1.0];
        
    }
}

-(void)clearnTimer
{
    if (self.timer)
    {
        [self.timer invalidate];
        self.timer = nil;
    }
}
#pragma mark 创建通话时间计时器
-(void)createTimer
{
    if (self.timer==nil)
    {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(calculateCallTime:) userInfo:nil repeats:YES];
    }
}
#pragma mark 通话时间
-(void)calculateCallTime:(id)sender
{
    ssInt +=1;
    if (ssInt >= 60)
    {
        mmInt += 1;
        ssInt -= 60;
        if (mmInt >=  60)
        {
            hhInt += 1;
            mmInt -= 60;
            if (hhInt >= 24)
            {
                hhInt = 0;
            }
        }
    }
    if (hhInt > 0) {
        self.labStatus.text = [NSString stringWithFormat:@"%02d:%02d:%02d",hhInt,mmInt,ssInt];
    }
    else
    {
        self.labStatus.text = [NSString stringWithFormat:@"%02d:%02d",mmInt,ssInt];
    }
    
}
//取消打拔
-(void)callBack:(id)sender
{
    if (_dialType==0)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CALLSTATENOTIFICATION" object:nil];
        [self clearnTimer];
       // pjsuaHangup(true);
    }else if (_dialType==1)
    {
        if (self.requestCallingData)
        {
            [self.requestCallingData cancel];
        }
        //[NSObject cancelPreviousPerformRequestsWithTarget:self
                                                 //selector:@selector(call:)
                                                  // object:nil];
        //[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(callBack:) object:nil];
    }
    [self dismissModalViewControllerAnimated:YES];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self showAdv];
}
-(void)viewWillDisappear:(BOOL)animated
{
    if ([callPlayer isPlaying])
    {
        [callPlayer stop];
    }
    if (barnnerView)
    {
        [barnnerView stop];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CALLSTATENOTIFICATION" object:nil];
    [super viewWillDisappear:animated];
    
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)dealloc
{
    
    shareCallViewControllerInstance=nil;
    [array release];
    [callNum release];
    [name release];
    [number release];
    [super dealloc];
}

@end
